package com.itheima.interceptor;

import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuyp
 * @since 2025/7/26
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果没有token：直接返回false，响应码设置为401
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            response.setStatus(401);
            return false;
        }

        //如果有token，校验token不通过：直接返回false，响应码设置为401
        try {
            Claims body = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return false;
        }

        //返回true
        return true;
    }
}
